package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"time"
	"zhihu/models/cache"
	"zhihu/models/mysql"

	"zhihu/zhihuRpc/internal/svc"
	"zhihu/zhihuRpc/zhihuRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type QuestionListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQuestionListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QuestionListLogic {
	return &QuestionListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *QuestionListLogic) QuestionList(in *zhihuRpc.QuestionListRequest) (*zhihuRpc.QuestionListResponse, error) {
	// todo: add your logic here and delete this line

	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	key := fmt.Sprintf("problemList_%d_%d", in.Page, in.Size)
	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	var questions []mysql.Question

	if result == "" {
		mysql.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).
			Order("created_at desc").Find(&questions)

		marshal, _ := json.Marshal(questions)

		cache.Rdb.Set(l.ctx, key, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(result), &questions)
	}

	var questionList []*zhihuRpc.ListQuestion

	for _, problem := range questions {
		list := zhihuRpc.ListQuestion{
			Id:      int64(problem.ID),
			Content: problem.Content,
			UserId:  problem.UserId,
		}

		questionList = append(questionList, &list)
	}

	return &zhihuRpc.QuestionListResponse{
		List: questionList,
	}, nil
}
